import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_xxyk/constant/routes.dart';
import 'package:flutter_xxyk/pages/home.dart';
import 'package:flutter_xxyk/pages/login.dart';
import 'package:flutter_xxyk/pages/products/column_detail_page.dart';
import 'package:flutter_xxyk/pages/profile_detail.dart';
import 'package:flutter_xxyk/util/dio_util.dart';
import 'package:sp_util/sp_util.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SpUtil.getInstance();
  handleError(() => runApp(MyApp()));
}

void handleError(void Function() body) {
  /// 重写Flutter异常回调 FlutterError.onError
  FlutterError.onError = (FlutterErrorDetails details) {
    // debug时，直接将异常信息打印。
    FlutterError.dumpErrorToConsole(details);
  };

  /// 使用runZonedGuarded捕获Flutter未捕获的异常
  runZonedGuarded(body, (Object error, StackTrace stackTrace) async {
    debugPrintStack(
      stackTrace: stackTrace,
      label: error.toString(),
      maxFrames: 100,
    );
  });
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key) {
    DioUtil.initDio(navKey);
  }

  final GlobalKey<NavigatorState>? navKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navKey,
      title: "Xxyk",
      debugShowCheckedModeBanner: false,
      theme: Theme.of(context).copyWith(platform: TargetPlatform.iOS, cardTheme: CardTheme(shadowColor: Color(0x80DCE7FA))),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', 'US'), // 美国英语
        const Locale('zh', 'CN'), // 中文简体
        //其它Locales
      ],
      initialRoute: AppRoutes.HOME,
      routes: {
        AppRoutes.HOME: (context) => Home(),
        AppRoutes.LOGIN: (context) => Login(),
        AppRoutes.PROFILE_DETAIL: (context) => ProfileDetail(),
        AppRoutes.COLUMN_DETAIL: (context) => ColumnDetailPage(),
      },
    );
  }
}
